package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;


import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 套餐服务实现类
 */

@Transactional
@Service(interfaceClass = SetMealService.class )
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;

    // freemaker
    @Autowired
    private FreeMarkerConfigurer configurer;
    @Value("${output_path}")
    String output_path;

    /**
     * 分页查询套餐
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        // 初始化pageHelper(threadLocal存page,size)
        PageHelper.startPage(currentPage, pageSize);
        // 拦截dao查询的结果,故该查询语句一定要在startPage的下一行;
        List<Setmeal> items = setMealDao.findPage(queryString);
        // 处理拦截的结果
        PageInfo<Setmeal> pageInfo = new PageInfo<>(items);
        List<Setmeal> list = pageInfo.getList();
        long total = pageInfo.getTotal();
        return new PageResult(total, list);
    }

    /**
     * 查询所有检查组
     * @return
     */
    @Override
    public List<CheckGroup> findAll() {
        return setMealDao.findAll();
    }

    /**
     * 添加套餐
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        // 向t_setmeal添加套餐
        setMealDao.addSetmeal(setmeal);
        // 中间关系表添加关系
        setCheckGroupAndSetmeal(setmeal.getId(), checkgroupIds);

        // 添加时生出所有页面
        createAllStaticHtml();

    }


    /**
     * 添加时批量生成页面
     */
    private void createAllStaticHtml() {
        List<Setmeal> setmealList = this.getAllSetMeal();
        // 更新套餐静态页面
        updateSetmealHtml();
        // 生成所有套餐详情页面
        createSetmealDetailHtmlByList(setmealList);

    }

    /**
     * 生成所有套餐详情页面
      * @param setmealList
     */
    private void createSetmealDetailHtmlByList(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            updateSetmealDetailHtml(setmeal);
        }
    }

    /**
     * 跟新对应套餐的详情页面
     * @param setmeal
     */
    private void updateSetmealDetailHtml(Setmeal setmeal) {
        // 创建容器
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmeal", setmeal);
        // 创建页面
        CreateStaticHtml(map,"setmeal_id_detail.ftl","setmeal_" + setmeal.getId() + "_detail.html");

    }

    /**
     * 根据套餐id删除套餐详情页面
     * @param setmealId
     */
    private void deleteSetmealDetailHtml(Integer setmealId) {
        String fileName = "setmeal_" + setmealId + "_detail.html";
        File fileOut = new File(output_path + "\\" + fileName);
        // 删除页面
        fileOut.delete();
    }


    /**
     * 跟新套餐页面
     */
    private void updateSetmealHtml() {
        List<Setmeal> setmealList = this.getAllSetMeal();
        // 创建容器
        HashMap<String, Object> map = new HashMap<>();
        // 查询所有套餐
        map.put("setmealList", setmealList);
        // 创建页面
        CreateStaticHtml(map,"setmeal.ftl","setmeal.html");
    }

    /**
     * 生成静态页面
     * @param map
     * @param templateName
     * @param fileName
     */
    private void CreateStaticHtml(Map<String,Object> map, String templateName, String fileName) {
        BufferedWriter bufferedWriter = null;
        try {
            Configuration configuration = configurer.getConfiguration();
            // 加载模板
            Template template = configuration.getTemplate(templateName);
            // 创建输出流
            File fileOut = new File(output_path + "\\" + fileName);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut)));
            // 模板生成
            template.process(map,bufferedWriter);
            // 释放资源

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setMealDao.findById(id);
        List<CheckGroup> checkGroups = setmeal.getCheckGroups();
        List<Integer> checkGroupIds = new ArrayList<>();
        if (checkGroups != null && checkGroups.size() > 0) {
            for (CheckGroup checkGroup : checkGroups) {
                checkGroupIds.add(checkGroup.getId());
            }
        }
        setmeal.setCheckGroupIds(checkGroupIds);
        return setmeal;

    }


    /**
     * 编辑套餐
     * @param setmeal
     */
    @Override
    public void updateSetmeal(Setmeal setmeal) {
        // 清除原有的group与Setmeal的中间关系
        setMealDao.release(setmeal);
        // 将list集合转成数组Object[]
        List<Integer> list = setmeal.getCheckGroupIds();
        Object[] groupIds = list.toArray();
        // 再添加新的关系
        setCheckGroupAndSetmeal(setmeal.getId(), groupIds);
        // 更新套餐信息
        setMealDao.updateSetmeal(setmeal);

        // 更新套餐页面
        this.updateSetmealHtml();
        // 更新套餐详情页面
        this.updateSetmealDetailHtml(setmeal);


    }

    /**
     * 删除套餐
     * @param id
     */
    @Override
    public void deleteSetmeal(Integer id) {

        // order里面有没有套餐.有则不能删除
        int order = setMealDao.isContainedInOrder(id);
        if (order > 0) {
            throw new RuntimeException(MessageConstant.SETMEALL_IS_CONTAIN_IN_ORDER);
        }
        // 确认套餐是否包含检查组,有则不能删除
        int groups = setMealDao.isContainGroups(id);
        if (groups > 0) {
            throw new RuntimeException(MessageConstant.GROUP_IS_CONTAINED_IN_SETMEAL);
        }

        // 删除套餐
        setMealDao.deleteSetmeal(id);

        // 更新套餐页面
        this.updateSetmealHtml();
        // 删除套餐详情页面
        this.deleteSetmealDetailHtml(id);

    }

    /**
     * 查询所有套餐信息
     * @return
     */
    @Override
    public List<Setmeal> getAllSetMeal() {
        return setMealDao.getAllSetMeal();
    }

    private void setCheckGroupAndSetmeal(Integer setmealId, Object[] checkgroupIds) {
        // checkgroupIds,才添加
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            HashMap<String, Object> map = new HashMap<>();

            // 遍历checkgroupIds 添加数据到中间关系表
            for (Object checkgroupId : checkgroupIds) {
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setMealDao.setCheckGroupAndSetmeal(map);
            }
        }
    }
}
